package ch.pizzapp.kurier;

import java.util.List;
import java.util.Locale;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import ch.pizzapp.kurier.adapter.PlaceAdapter;
import ch.pizzapp.kurier.client.InfoClient;
import ch.pizzapp.kurier.data.PlaceData;
import ch.pizzapp.kurier.data.PlaceResponceData;
import ch.pizzapp.kurier.data.ResponceData;
import ch.pizzapp.kurier.data.UserResonce;

/**
 * A placeholder fragment containing a simple view.
 */
@EFragment(R.layout.fragment_places)
public class PlaceFragment extends Fragment {

	@ViewById(R.id.location)
	EditText location;

	@Bean
	PlaceAdapter placeAdapter;

	@FragmentArg("ResponceData")
	ResponceData responceData;

	@FragmentArg("UserResonce")
	UserResonce userResonce;

	public PlaceFragment() {
	}

	public interface Callback {
		void clickPlace(PlaceData placeDataItem);

	}

	Callback mCallback;

	public void setOnCallback(Callback mCallback) {
		this.mCallback = mCallback;
	}

	public static PlaceFragment newInstance(ResponceData responceData,
			UserResonce userResonce) {
		PlaceFragment fragment = new PlaceFragment_();
		Bundle args = new Bundle();
		args.putParcelable("ResponceData", responceData);
		args.putParcelable("UserResonce", userResonce);
		fragment.setArguments(args);
		return fragment;
	}

	public void hideKeyboard(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		// Find the currently focused view, so we can grab the correct window
		// token from it.
		View view = activity.getCurrentFocus();
		// If no view currently has focus, create a new one, just so we can grab
		// a window token from it
		if (view == null) {
			view = new View(activity);
		}
		inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	@RestService
	InfoClient infoClient;

	@AfterViews
	void iniUi() {
		location.addTextChangedListener(textWatcher);

		placeAdapter.setOnCallback(new PlaceAdapter.Callback() {

			@Override
			public void clickPlace(PlaceData placeDataItem) {
				// TODO Auto-generated method stub
				// System.out.println("placeDataItem " +
				// placeDataItem.getTitle());

				if (mCallback != null) {
					getActivity().getSupportFragmentManager()
							.beginTransaction().remove(PlaceFragment.this)
							.commit();
					mCallback.clickPlace(placeDataItem);

				} else {
					getActivity().finish();
					Intent intent = new Intent(getActivity(),
							DrawerActivity_.class);
					if (responceData != null) {
						intent.putExtra("ResponceData", responceData);
						
					}
					
					intent.putExtra("PlaceDataItem", placeDataItem);
					intent.putExtra("UserResonce", userResonce);
					startActivity(intent);
					getActivity().overridePendingTransition(R.anim.from_middle,
							R.anim.to_middle);
				}
			}

		});
	}

	private TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			// System.out.println("test");
			String text = location.getText().toString()
					.toLowerCase(Locale.getDefault());
			placeAdapter.filter(text);
		};

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

	};

	@AfterViews
	@Background
	void getPlace() {

		final MultiValueMap<String, String> mvMap = new LinkedMultiValueMap<String, String>();

		mvMap.add("type", "10");

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setPlace(infoClient.getPlaces(mvMap));
				} catch (Exception e) {
					showProgress(false);
					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {
				showProgress(false);
				showMessge("Not connected ");
			}
		});
	}

	@UiThread
	void setPlace(final PlaceResponceData placeResponceData) {

		showProgress(false);
		List<PlaceData> placeList = placeResponceData.getResponse()
				.getPlaceDataDataList();

		if (placeList != null) {
			placeAdapter.setPlaceDataDataOri(placeList);
			listViewPlace.setAdapter(placeAdapter);
		}

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	@ViewById(R.id.login_status)
	protected LinearLayout mLoginStatusView;
	@ViewById(R.id.listViewPlace)
	ListView listViewPlace;

	@UiThread
	void showProgress(final boolean show) {

		// The ViewPropertyAnimator APIs are not available, so simply show
		// and hide the relevant UI components.
		mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
		listViewPlace.setVisibility(show ? View.GONE : View.VISIBLE);

	}

	@Override
	public void onStop() {
		super.onStop();
		showProgress(false);
	}

}